package com.zhijian.medical.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhijian.medical.dao.local.RoutinePatientExceptionMapper;
import com.zhijian.medical.entity.po.RoutinePatient;
import com.zhijian.medical.entity.po.RoutinePatientException;
import com.zhijian.medical.enums.PatientEnums;
import com.zhijian.medical.enums.RoutinePathologySampleStepEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class RoutinePatientExceptionService {

    @Autowired
    RoutinePatientExceptionMapper routinePatientExceptionMapper;

    @Autowired
    RoutinePatientService routinePatientService;

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    public RoutinePatientException addAndUpdException(RoutinePatientException routinePatientException){
        RoutinePatientException oneData = readException(routinePatientException.getPatientId(), routinePatientException.getExType());
        if (oneData != null){
            routinePatientException.setId(oneData.getId());
            routinePatientExceptionMapper.updateById(routinePatientException);
        }else {
            routinePatientException.setHandleTime(new Date());
            routinePatientExceptionMapper.insert(routinePatientException);
        }
        updatePatientState(routinePatientException.getPatientId(), routinePatientException.getExType());
        return routinePatientException;
    }

    private void updatePatientState(Long patientId, Integer exType){
        Integer state = PatientEnums.PatientStateEnum.OFF_BODY_EXCEPTION.getCode();
        if (RoutinePathologySampleStepEnum.GD.getCode().equals(exType)){
            //固定异常
            state = PatientEnums.PatientStateEnum.GD_EXCEPTION.getCode();
        }
        RoutinePatient upd = new RoutinePatient();
        upd.setId(patientId);
        upd.setState(state);
        routinePatientService.updateByPrimaryKeySelective(upd);
    }

    public RoutinePatientException readException(Long patientId, RoutinePathologySampleStepEnum routinePathologySampleStepEnum){
        return readException(patientId, routinePathologySampleStepEnum.getCode());
    }

    private RoutinePatientException readException(Long patientId, Integer exType){
        QueryWrapper<RoutinePatientException> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_id", patientId);
        queryWrapper.eq("ex_type", exType);
        return routinePatientExceptionMapper.selectOne(queryWrapper);
    }
}
